package core

import (
	"fmt"
	"project-init/plugin"

	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
)

func BuildMainMenu(app *tview.Application) *tview.List {
	list := tview.NewList()
	for _, tmpl := range plugin.Templates {
		t := tmpl
		list.AddItem(t.Name(), "", 0, func() {
			app.SetRoot(BuildDirSelectMenu(app, t), true)
		})
	}
	list.AddItem("Load Remote Template", "", 0, func() {
		app.SetRoot(BuildRemoteInput(app), true)
	})
	return list
}

func BuildRemoteInput(app *tview.Application) tview.Primitive {
	var input *tview.InputField
	input = tview.NewInputField().
		SetLabel("Enter remote template URL: ").
		SetDoneFunc(func(key tcell.Key) {
			if key == tcell.KeyEnter {
				url := input.GetText()
				if url != "" {
					err := plugin.LoadRemoteTemplate(url)
					if err != nil {
						app.Stop()
						panic(err)
					}
				}
				app.SetRoot(BuildMainMenu(app), true)
			}
		})
	flex := tview.NewFlex().AddItem(input, 0, 1, true)
	return flex
}

// BuildDirSelectMenu 目录选择菜单（简化版）
func BuildDirSelectMenu(app *tview.Application, tmpl plugin.Template) tview.Primitive {
	selected := tmpl.Dirs()
	button := tview.NewButton("Confirm and Create").
		SetSelectedFunc(func() {
			err := createJavaProjectStructure(".", selected)
			if err != nil {
				app.Stop()
				panic(err)
			}
			writeFiles(tmpl.Files())
			_ = InitGitRepo()
			app.Stop()
			fmt.Println("✅ Project structure created.")
		})
	flex := tview.NewFlex().SetDirection(tview.FlexRow).
		AddItem(tview.NewTextView().SetText("Selected Dirs:"), 1, 0, false).
		AddItem(tview.NewTextView().SetText(fmt.Sprintf("%v", selected)), 1, 0, false).
		AddItem(button, 1, 0, true)
	return flex
}
